/*
 * Copyright (c) 2019 Author: Fancyears Milos Malvis @1243093366@qq.com
 * ALL COPYRIGHT REVERSED.
 */

package com.fancyears.handler;

import com.alibaba.fastjson.JSONObject;
import com.fancyears.global.GlobalSetting;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局的异常处理器，用于打印日志
 * @Author: Fancyears Milos Malvis
 * @Date: Created in  2019/5/10 9:22
 * @Modified By:
 */
@ControllerAdvice(annotations = {Controller.class,RestController.class})
@Slf4j
public class GlobalExceptionHandler {
    @Value("${ServerErrorMsg}")
    private String serverErrorMsg;


    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        log.error(ExceptionUtils.getStackTrace(e));  // 记录错误信息
        String msg = e.getMessage();
        if (StringUtils.isEmpty(msg)) {
            msg = serverErrorMsg;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(GlobalSetting.MESSAGE, msg);
        return GlobalSetting.ERROR_PAGE;
    }
}
